先來寫個簡單的 Javascript 版本 CRUD 之前先參考 bs-mongodb
但是要先寫一個 CRUD JS 版本範例
mongodbManager.js
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'myproject';
class mongoDBManagerClass {
initialDB({url, dbName}){
return MongoClient.connect(url, { useNewUrlParser: true })
.then(client => {
this._client = client;
this._db = client.db(dbName);
this._document = this._db.collection('documents');
});
}
insertManyDocument(array) {
return this._document.insertMany(array);
}
findDocuments(query) {
return this._document.find({});
}
updateDocuments(query, updateQuery) {
return this._document.update(query, updateQuery);
}
deleteDocuments(query) {
return this._document.deleteMany(query);
}
closeClient() {
this._client.close();
}
}
const mongoDBManager = new mongoDBManagerClass({url, dbName});
module.exports = mongoDBManager;
app.js
const mongoDBManager = require('./mongodbManager');
mongoDBManager
.initialDB({url, dbName})
.then(() => mongoDBManager.insertManyDocument([{a : 1}]))
.then((resp) => console.log(resp))
.then(() => mongoDBManager.updateDocuments({a: 1}, {a: 2}))
.then((resp) => console.log(resp))
.then(() => mongoDBManager.findDocuments({a: 2}))
.then((resp) => console.log(resp))
.then(() => mongoDBManager.deleteDocuments({a: 2}))
.then((resp) => console.log(resp))
.then(() => mongoDBManager.closeClient())
.catch(error => console.log("error", error));
上述例子是一個簡單的 MongoDB
的 CRUD
再來慢慢將它轉為 MongoDBManager.re
吧
先初始化一個 MongoClient